package com.sdp.wx.controller;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.flowable.engine.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.flow.db.entity.ActHiComment;
import com.sdp.flow.db.entity.ActHiTaskinst;
import com.sdp.flow.db.service.IActHiTaskinstService;
import com.sdp.flow.db.service.IWorkflowService;
import com.sdp.wx.db.wx_emp.entity.WxEmp;
import com.sdp.wx.db.wx_emp.service.IWxEmpService;

@RestController
@RequestMapping("/WorkFlowController")
public class WorkFlowController {
	
	@Autowired
	private Query query;
	
	@Autowired
	private IActHiTaskinstService hiTaskinstService;
	
	@Autowired
    protected HistoryService historyService;
	
	@Autowired
	private IWorkflowService workflowService;
	
	@Autowired
	private IWxEmpService iWxEmpService;
	

	@PostMapping(value="/instanceTask")
	public Result<?> instanceTask(@RequestBody DataCenter dataCenter) {
		List<ActHiTaskinst> actHiTaskinstList = query.list(hiTaskinstService, ActHiTaskinst.class, dataCenter);
		if(actHiTaskinstList!=null && actHiTaskinstList.size()>0) {
			
			//获取人信息
			List<String> empNos = new ArrayList<String>();
			for(ActHiTaskinst actHiTaskinst : actHiTaskinstList) {
				empNos.add(actHiTaskinst.getAssignee());
			}
			Map<String,WxEmp> empMap = new HashMap<>();
			List<WxEmp> empList = iWxEmpService.queryEmpsByEmpNos(empNos);
			for(WxEmp emp : empList) {
				empMap.put(emp.getEmpNo(), emp);
			}
			
			//查询审批意见信息
			List<ActHiComment> commentList = workflowService.getApprovedOpinionNew(actHiTaskinstList.get(0).getProcInstId());
			
			for(ActHiTaskinst actHiTaskinst : actHiTaskinstList) {
				if(empMap.containsKey(actHiTaskinst.getAssignee())) {
					actHiTaskinst.setUserAvatar(empMap.get(actHiTaskinst.getAssignee()).getProfilePicture());
					actHiTaskinst.setUserName(empMap.get(actHiTaskinst.getAssignee()).getEmpName());
				}
				if (commentList != null && commentList.size() > 0) {
					for(ActHiComment actHiComment : commentList) {
						if(actHiTaskinst.getId().equals(actHiComment.getTaskId())) {
							actHiTaskinst.setUserSign(actHiComment.getUserSign());
							actHiTaskinst.setIsPass(actHiComment.getIsPass());
							actHiTaskinst.setOpinion(actHiComment.getMessage());
							actHiTaskinst.setProcessingTime(LocalDateTime.ofInstant(actHiComment.getTime().toInstant(), ZoneId.systemDefault()));
						}
					}
				}
			}
		}
		
		return Result.ok(actHiTaskinstList);
	}

}
